package com.ckd.flyingtrip.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.github.gcacace.signaturepad.views.SignaturePad;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MyZhanghuPactActivity extends BaseActivity {

    @BindView(R.id.toolber_color_title)
    TextView title;
    @BindView(R.id.activity_my_zhanghu_pact_textView)
    TextView textView;
    @BindView(R.id.activity_my_zhanghu_pact_agreell)
    LinearLayout agreell;
    @BindView(R.id.activity_my_zhanghu_pact_nestedScrollView)
    NestedScrollView scrollView;
    @BindView(R.id.activity_my_zhanghu_pact_signature)
    SignaturePad signatureView;
    @BindView(R.id.activity_my_zhanghu_pact_agree)
    TextView agree;
    private String str = "1";
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_zhanghu_pact);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();

    }

    private void initListener() {
        signatureView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (v.getId() == R.id.activity_my_zhanghu_pact_signature) {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                    }
                }
                return false;
            }
        });

        signatureView.setOnSignedListener(new SignaturePad.OnSignedListener() {
            @Override
            public void onStartSigning() {

            }

            @Override
            public void onSigned() {
                str = "2";
            }

            @Override
            public void onClear() {
                str = "1";
            }
        });
    }

    private void initView() {
        title.setText("租车协议");
    }

    private void initData() {
        final Gson mGson = new Gson();
        String url = Constants.useragreement;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("协议", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String data = json.getString("data");
                        textView.setText(data);
                    } else {
                        Log.i("站好", "账号");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        });
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    @OnClick({R.id.activity_my_zhanghu_pact_agree, R.id.activity_my_zhanghu_pact_disagree, R.id.activity_my_zhanghu_pact_cancel,
            R.id.activity_my_zhanghu_pact_complete, R.id.toolber_color_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolber_color_back:
                finish();
                break;
            case R.id.activity_my_zhanghu_pact_agree:
                agree.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                agree.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                agreell.setVisibility(View.VISIBLE);
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(NestedScrollView.FOCUS_DOWN);
                    }
                });
                break;
            case R.id.activity_my_zhanghu_pact_disagree:
                finish();
                break;
            case R.id.activity_my_zhanghu_pact_cancel:
                if (str.equals("1")) {
                    return;
                }
                signatureView.clear();
                break;
            case R.id.activity_my_zhanghu_pact_complete:
                if (str.equals("1")) {
                    toast("请先签名！");
                    return;
                }
                createLoadingDialog(this, "上传图片中,请稍后...", true);
                try {
                    Bitmap signatureBitmap = signatureView.getSignatureBitmap();
                    getWindow().getDecorView().setDrawingCacheEnabled(true);
                    Bitmap bmp = getWindow().getDecorView().getDrawingCache();
                    file = saveFile(compressBitmap(bmp, 200), getTime());
                    initComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void initComplete() {
        JSONObject json_url = new JSONObject();
        try {
            json_url.put("userId", BcUtils.getUid());
            json_url.put("suffix", ".png");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.post()
                .addParams("inputParameter", DataCheck.signCheck(json_url.toString()))
                .addFile("uploadImage", System.currentTimeMillis() + ".png", file)
                .url(Constants.uploadsign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("上传签名照片", "" + e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("上传签名照片", response);
                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            if (code.equals("1")) {
                                BcUtils.getUserInfo().setUserSignState("1");
                                finish();
                            } else {
                                Log.i("站好", "账号");
                            }
                            dismisProgressDialog();
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismisProgressDialog();
                        }
                    }
                });
    }

    public File saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/Ask";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;
    }

    public String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String timeString = formatter.format(curDate);

        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
        Date d;
        try {
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStamp;
    }

    private Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length / 1024 > sizeLimit) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 10;
        }
        Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
        return newBitmap;
    }
}
